package cn.mall.org.service.impl;

import cn.mall.base.constants.BaseConstants;
import cn.mall.base.utils.LoginContext;
import cn.mall.base.utils.MD5Utils;
import cn.mall.base.utils.PageList;
import cn.mall.org.domain.Manager;
import cn.mall.org.domain.Shop;
import cn.mall.org.dto.ShopManagerDTO;
import cn.mall.org.dto.ShopRegisterDTO;
import cn.mall.org.mapper.ManagerMapper;
import cn.mall.org.mapper.ShopMapper;
import cn.mall.org.query.ShopQuery;
import cn.mall.org.service.IShopService;
import cn.mall.base.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author myf
 * @since 2023-12-02
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {


    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ManagerMapper managerMapper;

    @Override
    public void settlement(ShopRegisterDTO shopRegisterDTO) {
        ShopManagerDTO manager = shopRegisterDTO.getManager();
        //参数校验
        validate(shopRegisterDTO,manager);

        //保存商店信息
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopRegisterDTO,shop);
        shop.setRegisterTime(new Date());
        shop.setState(BaseConstants.ShopAudit.STATE_WAIT_AUTID);

        Manager managerByName=managerMapper.loadByUsername(manager.getUsername());
        Long managerId=null;
        if (Objects.nonNull(managerByName)){
            //管理员存在
            managerId=managerByName.getId();
            shop.setBusinessId(managerId);

        }else {
            //保存商家信息
            Manager manager1 = new Manager();
            BeanUtils.copyProperties(manager,manager1);
            String salt = UUID.randomUUID().toString();
            String md5Password = MD5Utils.encrypByMd5(salt + manager.getPassword() + "auth");
            manager1.setPassword(md5Password);
            manager1.setSalt(salt);
            manager1.setCreatetime(new Date());
            manager1.setType(BaseConstants.AuthAccountType.BUSINESS_TYPE);
            manager1.setDisable(BaseConstants.AccountDisable.ACCOUNTDISABLE);
            managerMapper.insert(manager1);
            shop.setBusinessId(manager1.getId());
        }

        shopMapper.insert(shop);

    }

    //店铺审核操作
    @Override
    public void examineBusiness(Long id) {
        Shop shop = shopMapper.loadById(id);
        Manager manager = managerMapper.loadById(shop.getBusinessId());
        if (manager.getDisable().equals(BaseConstants.AccountDisable.ACCOUNTDISABLE)){
            shopMapper.updateByState(id,BaseConstants.ShopAudit.STATE_NORMAL);
            managerMapper.updateByExamine(manager.getId(),BaseConstants.AccountDisable.ACCOUNTABLE);
        }else {
            shopMapper.updateByState(id,BaseConstants.ShopAudit.STATE_NORMAL);
        }
    }

    /**
     * 根据商家 id 获取店铺信息
     * @param id
     * @return
     */
    @Override
    public List<Shop> getShopsByUserId(Long id) {
        List<Shop> shops = shopMapper.getShopsByUserId(id);
        return shops;
    }

    @Override
    public PageList<Shop> pageList(ShopQuery query, Manager loginUser) {
        //查询总条数
        Long total = shopMapper.loadTotalById(query,loginUser.getId());
        if (total > 0){
            List<Shop> rows = shopMapper.pageListById(query,loginUser.getId());
            return new PageList<Shop>(total, rows);
        }
        return new PageList<>();
    }


    //参数非空校验
    private void validate(ShopRegisterDTO shopRegisterDTO, ShopManagerDTO managerDTO){
        if (Objects.isNull(shopRegisterDTO) || Objects.isNull(managerDTO)|| StringUtils.isEmpty(shopRegisterDTO.getName())
                ||StringUtils.isEmpty(managerDTO.getUsername()) ||StringUtils.isEmpty(managerDTO.getPhone())
                ||StringUtils.isEmpty(managerDTO.getPassword()) ||StringUtils.isEmpty(managerDTO.getComfirmPassword())){
            throw new RuntimeException("信息不能为空，请检查后重新提交！");

        }
        if (!managerDTO.getPassword().equals(managerDTO.getComfirmPassword())){
            throw new RuntimeException("两次密码不一致");
        }

        Shop shopName=shopMapper.loadByName(shopRegisterDTO.getName());
        if (Objects.nonNull(shopName)){
            throw new RuntimeException("店铺已存在");
        }
    }
}
